package upc.dew.inscripcionalumnos.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import org.springframework.web.servlet.view.RedirectView;
import upc.dew.inscripcionalumnos.model.Estado;
import upc.dew.inscripcionalumnos.model.Mail;
import upc.dew.inscripcionalumnos.model.Postulante;
import upc.dew.inscripcionalumnos.service.Service;
import upc.dew.inscripcionalumnos.util.ServerMail;

public class FichaController extends SimpleFormController
{
    private static final String PARAMETRO_ACCION = "accion";
    
    private static final String ACCION_GUARDAR_FICHA = "guardarFicha";
    
    private static final String ACCION_FINALIZAR_FICHA = "finalizarFicha";

    private static final String ACCION_CANCELAR = "cancelar";

    @Autowired
    private DateFormat dateFormat;

    @Autowired
    private Service service;

    @Override
    protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception
    {
        Map<String, Object> referenceData = new HashMap<String, Object>();
        referenceData.put("distritos", service.getCatalogoService().obtenerDistritos());
        referenceData.put("tiposDocumento", service.getCatalogoService().obtenerTiposDocumento());
        referenceData.put("generos", service.getCatalogoService().obtenerGeneros());
        referenceData.put("estadoscivil", service.getCatalogoService().obtenerEstadosCivil());
        referenceData.put("postulante", (Postulante) request.getSession().getAttribute("postulante"));
        
        return referenceData;
    }

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
    {   
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception
    {
        Postulante postulante = (Postulante) command;
        
        if(esAccionGuardar(request))
        {
            postulante = service.getPostulanteService().registrarPostulante(postulante);
            request.getSession().setAttribute("postulante", postulante);
        }
        else if(esAccionFinalizar(request))
        {
            postulante.setFase(1);
            postulante.setEstado(Estado.ENVIADO);
            postulante = service.getPostulanteService().registrarPostulante(postulante);

            enviarEmail(postulante.getNombre(), postulante.getEmail());

            return new ModelAndView("postulante_Fase_1_Confirmacion");
        }
        else if(esAccionCancelar(request))
        {
            return new ModelAndView(new RedirectView("login.do?accion=logout"));
        }

        return new ModelAndView(new RedirectView(getSuccessView()));
    }

    @Override
    protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception
    {
        request.getSession().setAttribute("postulante", (Postulante) command);
    }

    private void enviarEmail(String nombre, String email )
    {
        ServerMail.sendEmail(Mail.CORREO_ADMINISTRADOR, Mail.CORREO_ADMINISTRADOR, Mail.NOMBRE_ADMINISTRADOR,
               email, Mail.SUBJECT_FICHA_APROBADA,
               "<h3>Hola " + nombre
               + " tu ficha de inscripci&oacute;n ha sido enviada para evaluaci&oacute;n. </h3><br/><br/>"
               + "<img src="+Mail.IMG_URL_LOGO_UPC+" /><br/>"
               + "Universidad Peruana de Ciencias Aplicadas (UPC)",
               Mail.CONTENT_TYPE_HTML, "mlpaucara@live.com" );
    }

    private boolean esAccionGuardar(HttpServletRequest request)
    {
        return ACCION_GUARDAR_FICHA.equals(request.getParameter(PARAMETRO_ACCION));
    }

    private boolean esAccionFinalizar(HttpServletRequest request)
    {
        return ACCION_FINALIZAR_FICHA.equals(request.getParameter(PARAMETRO_ACCION));
    }

    private boolean esAccionCancelar(HttpServletRequest request)
    {
        return ACCION_CANCELAR.equals(request.getParameter(PARAMETRO_ACCION));
    }
}